<?php

include_once 'ZReader.php';
include_once 'ZSourceCollection.php';
include_once 'ZSourceItem.php';

class ZSourceReader extends ZReader {
    protected $cache    = 'source';

    /**
     * Generate command string
     * @return string
     */
    public function command() {
        return sprintf('sources %s %s %s %s %s %s %s'."\r\n",
            $this->session,
            $this->begin,
            $this->end,
            $this->timeZone,
            $this->languages,
            $this->types,
            $this->query
        );
    }

    /**
     * Parse data that receive from server to object
     * @param $callback
     * @param $state
     * @return ZSourceCollection
     */
    public function parse($callback, &$state) {
        $i = 0;
        $collections = new ZSourceCollection();

        $arr = array();

        $succeed = false;

        //Read data while not end of file
        while (!$this->eof()) {
            //Read the first block is the length of the data
            $numBytes = $this->readNum();

            if ($numBytes >= 0 && $numBytes < 0xffffffff) {
                //Read data
                if ($i == 0) {
                    $arr[] = $this->readStr($numBytes);
                }
                else {
                    $arr[] = $this->readNum($numBytes);
                }
                $i++;

                //Enough a item
                if ($i == 5) {
                    $sourceItem = new ZSourceItem($arr[0], $arr[1], $arr[2], $arr[3], $arr[4]);
                    $collections->addItem($sourceItem);
                    $arr = array();
                    $i = 0;

                    if (is_callable($callback)) {
                        $callback($sourceItem);
                    }
                }
                //Not succeeded
                $succeed = false;
            }
            else if ($numBytes == 0xffffffff) {
                $succeed = true;
            }
        }

        $state = $succeed ? ($collections->count()> 0 ? 1 : 0) : -1;

        return $collections;
    }

    /**
     * @param null  $callback   callback function when receive data
     * @return ZSourceCollection
     * @throws Exception
     */
    public function read($callback = null) {
        return parent::readData($callback);
    }
}

?>
